package user

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/internal/utils/errorhandler"
	"mall/service/forum/rpc/types/forum"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// #24.10.29#  后台用户注册
func (l *CreateUserLogic) CreateUser(in *forum.ForumUserInfo) (*forum.BaseIDResp, error) {
	if in.NickName == nil || len(strings.TrimSpace(*in.NickName)) == 0 {
		return nil, errorx.NewInvalidArgumentError("user.nicknameRequired")
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	now := time.Now()
	user := &model.ForumUser{
		UserNickname: strings.TrimSpace(*in.NickName),
		CreatedAt:    now,
		UpdatedAt:    now,
	}

	if in.Avatar != nil && len(strings.TrimSpace(*in.Avatar)) > 0 {
		user.UserAvatar = strings.TrimSpace(*in.Avatar)
	}
	if in.Email != nil && len(strings.TrimSpace(*in.Email)) > 0 {
		user.UserEmail = strings.TrimSpace(*in.Email)
	}
	if in.UserURL != nil && len(strings.TrimSpace(*in.UserURL)) > 0 {
		user.UserURL = strings.TrimSpace(*in.UserURL)
	}
	if in.Signature != nil && len(strings.TrimSpace(*in.Signature)) > 0 {
		user.Signature = strings.TrimSpace(*in.Signature)
	}
	if in.UserId != nil && *in.UserId > 0 {
		user.UserID = *in.UserId
	}
	if in.CreatedBy != nil && *in.CreatedBy > 0 {
		user.CreatedBy = *in.CreatedBy
	}
	if in.Status != nil {
		user.UserStatus = uint16(*in.Status)
	} else {
		user.UserStatus = uint16(globalkey.StatusEnabled)
	}

	rel := &model.ForumUserRel{}
	if len(in.NewMedia) > 0 {
		for idx, v := range in.NewMedia {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			var uri string
			if v.Uri != nil && len(*v.Uri) > 0 {
				uri = *v.Uri
				if len(url) == 0 {
					url = uri
				}
			}
			if len(url) == 0 {
				continue
			}

			var thumbnail uint8
			if v.Thumbnail != nil && *v.Thumbnail > 0 {
				thumbnail = uint8(*v.Thumbnail)
			}
			var order uint
			if v.Order != nil {
				order = uint(*v.Order)
			} else {
				order = uint(idx) + globalkey.AttachmentOrderOffset
			}
			var altText string
			if v.AltText != nil && len(*v.AltText) > 0 {
				altText = *v.AltText
			}

			var meta []string
			if v.Name != nil && len(*v.Name) > 0 {
				meta = append(meta, "filename:"+*v.Name)
				if len(altText) == 0 {
					altText = *v.Name
				}
			}
			if v.MetaData != nil && len(*v.MetaData) > 0 {
				meta = append(meta, *v.MetaData)
			}
			if v.MimeType != nil && len(*v.MimeType) > 0 {
				meta = append(meta, "mimeType:"+*v.MimeType)
			}
			var metaData string = strings.Join(meta, ";")

			var mediaId uint64
			if v.Id != nil && len(*v.Id) > 0 {
				if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
					mediaId = uint64(i)
				}
			}

			rel.Media = append(rel.Media, &model.ForumAttachmentRelationship{
				AttachmentID:        mediaId,
				AttachmentThumbnail: thumbnail,
				AttachmentOrder:     order,
				AttachmentImageURL:  url,
				AttachmentImageAlt:  altText,
				AttachmentImageMeta: metaData,
			})
		}
	}

	err = l.svcCtx.User.Insert(l.ctx, tx, user, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &forum.BaseIDResp{
		Id:  user.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
